/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.server;

import com.google.orkut.client.transport.HttpRequest;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;

/**
 * Adapts a orkut-os-client's {@link HttpRequest} to oauth-signpost's
 * {@link oauth.signpost.http.HttpRequest}.
 *
 * @author Shishir Birmiwal
 */
public class HttpRequestAdapter implements oauth.signpost.http.HttpRequest {
  private final HttpRequest request;

  public HttpRequestAdapter(HttpRequest request) {
    this.request = request;
  }

  @Override
  public Map<String, String> getAllHeaders() {
    throw new UnsupportedOperationException("cannot get all headers");
  }

  @Override
  public String getContentType() {
    return getHeader("Content-Type");
  }

  @Override
  public String getHeader(String headerName) {
    Collection<HttpRequest.Header> headers = request.getHeaders();
    for (HttpRequest.Header header : headers) {
      if (header.getName().equals(headerName)) {
        return header.getValue();
      }
    }
    return null;
  }

  @Override
  public InputStream getMessagePayload() throws IOException {
    return new ByteArrayInputStream(request.getRequestBody());
  }

  @Override
  public String getMethod() {
    return request.getMethod();
  }

  @Override
  public String getRequestUrl() {
    return getUrl(request);
  }

  @Override
  public void setHeader(String arg0, String arg1) {
    request.addHeader(arg0, arg1);
  }

  @Override
  public void setRequestUrl(String arg0) {
    throw new UnsupportedOperationException("cannot set request url");
  }

  public static String getUrl(HttpRequest request) {
    StringBuffer url = new StringBuffer(request.getRequestBaseUrl());
    url.append("?");
    Collection<HttpRequest.Parameter> params = request.getParameters();
    for (HttpRequest.Parameter param : params) {
      url.append(param.getKey() + "=" + param.getValue());
    }
    return url.toString();
  }
}
